import requests
from bs4 import BeautifulSoup
from flask import Flask, render_template, request, redirect, url_for
from models import db, Category, Website

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///navigation_site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)


def fetch_website_info(url):

    # 为了模拟浏览器行为，你需要在使用 requests 发起请求时设置合适的 User-Agent。
    # 这里是一个修改后的 fetch_website_info 函数示例，它包含了设置自定义 User-Agent 的代码：
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)
        # 确保正确处理编码
        response.encoding = response.apparent_encoding if response.apparent_encoding else 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')
        title = soup.title.string.strip() if soup.title else url
        meta_desc = soup.find('meta', attrs={'name': 'description'})
        description = meta_desc['content'].strip() if meta_desc and 'content' in meta_desc.attrs else ''
        return title, description
    except Exception as e:
        print(f"Error fetching {url}: {e}")
        return url, ""


@app.route('/')
def index():
    categories = Category.query.all()
    return render_template('index.html', categories=categories)


@app.route('/admin', methods=['GET', 'POST'])
def admin():
    if request.method == 'POST':
        action = request.form.get('action')

        if action == 'add_category':
            name = request.form.get('category_name')
            if name:
                new_category = Category(name=name)
                db.session.add(new_category)
                db.session.commit()

        elif action == 'add_website':
            url = request.form.get('website_url')
            category_id = request.form.get('category_id')
            if url and category_id:
                title, description = fetch_website_info(url)
                new_website = Website(
                    url=url,
                    title=title,
                    description=description,
                    category_id=category_id
                )
                db.session.add(new_website)
                db.session.commit()

        elif action == 'delete_website':
            website_id = request.form.get('website_id')
            if website_id:
                website = Website.query.get(website_id)
                if website:
                    db.session.delete(website)
                    db.session.commit()

        elif action == 'delete_category':
            category_id = request.form.get('category_id')
            if category_id:
                category = Category.query.get(category_id)
                if category:
                    # 确保删除分类前先删除该分类下的所有网站
                    for website in category.websites:
                        db.session.delete(website)
                    db.session.delete(category)
                    db.session.commit()


    categories = Category.query.all()
    websites = Website.query.all()
    return render_template('admin.html', categories=categories, websites=websites)


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=80, debug=True)